<?php

namespace App\Http\Controllers\Front;

use App\Interfaces\BrandService;
use App\Interfaces\CategoryService;
use App\Interfaces\GoodsService;
use App\Interfaces\SearchKeywordsService;
use App\Interfaces\SolrService;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
use Auth,Session;
use Illuminate\Support\Collection;

class SearchController extends Controller
{

    public function index(Request $request,SearchKeywordsService $searchKeywordsService,CategoryService $categoryService,BrandService $brandService,GoodsService $goodsService,SolrService $solrService)
    {

        $keyword = $request->get('keyword');
        $keyword = str_replace("("," ",$keyword);
        $keyword = str_replace(")"," ",$keyword);
        $keyword = addslashes($keyword);
        $filter['keyword'] = addslashes($request->get('keyword'));
        $filter['cat_id'] = $request->get('cat_id');
        $filter['brand_id'] = $request->get('brand_id')?$request->get('brand_id'):0;
        $filter['stock'] = $request->get('stock')?$request->get('stock'):0;
        $filter['sort'] = $request->get('sort');

        // $keyword = $filter['keyword'];

        $result = $solrService->search($keyword,$filter['cat_id'],$filter['brand_id'],$filter['stock'],$request->get('page'),40,$filter['sort']);

        $goodsPaginate = $result['paginate'];

        $brandFacet = $result['facetSet']->getFacet('brand_id')->getValues();

        //检索品牌
        $filterBrand = $brandService->getBrandByIds(array_keys($brandFacet));


        //相似关键词

        if ($filter['keyword']!=''){
            $relateKeywords = $solrService->suggest($filter['keyword'],10);
        }else{
            $relateKeywords = new Collection();//dd($relateKeywords);
        }

        if (preg_match('/^af|KS|ASKF|BL|BYJ|HT|JD|MDL|SPH\d*$/',$filter['keyword'])){

            $goods = $goodsService->getGoodsBySn($filter['keyword']);

            if ($goods){
                return redirect('/goods/'.$goods->goods_id);
            }
        }

        //用户信息
        $user=Auth::user();


        return view('front.search.index',compact(['goodsPaginate','relateKeywords','filter','filterCategory','filterBrand','brandFacet','keyword','user']));

    }

    public function suggestion(Request $request,SolrService $solrService){

        $keyword = $request->get('keyword');
        
        $result = $solrService->suggest($keyword,15);

        return Response()->json($result);

    }


}
